762C - Two strings - CodeForces Solution


binary search hashing strings two pointers *2100

Please click on ads to support us..

Python Code:

import sys
 
input = sys.stdin.readline
 
def solve():
	a = input().strip()
	b = input().strip()
 
	n = len(a)
	m = len(b)
	c = [0]*m
	d = [0]*m
 
	p = 0
	for i in range(m):
		for j in range(p, n):
			if a[j] == b[i]:
				c[i] = j
				p = j + 1
				break
		else:
			for j in range(i,m):
				c[j] = n
			break
	p = n-1
	for i in range(m-1,-1,-1):
		for j in range(p,-1,-1):
			if a[j] == b[i]:
				d[i] = j
				p = j - 1
				break
		else:
			for j in range(i,-1,-1):
				d[j] = -1
			break
	j = 0
	while j < m and d[j] < 0:
		j += 1
	res = (m-j, 0, j)
	for i in range(m):
		p = c[i]
		if p == n:
			break
		while j < m and (j <= i or d[j] <= p):
			j += 1
		res = max(res,(i+1+m-j,i+1,j))
	if res[0] == 0:
		print('-')
	else:
		print(b[:res[1]]+b[res[2]:])
 
solve()

C++ Code:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = 1e5 + 10;
ll pre[N], suf[N];
char s[N], t[N];
int main() {
    scanf("%s%s", s + 1, t + 1);
    ll n1 = strlen(s + 1), n2 = strlen(t + 1), last = 0;
    for (ll i = 1; i <= n1; i++) {
        pre[i] = n2, suf[i] = 1;
    }
    suf[n1 + 1] = n2 + 1;
    for (ll i = 1, j = 1; i <= n1 && j <= n2; i++) {
        if (s[i] == t[j]) {
            last = j;
            j++ ;
        }
        pre[i] = last;
    }
    last = n2 + 1;
    for (ll i = n1, j = n2; i >= 1 && j >= 1; i--) {
        if (s[i] == t[j]) {
            last = j;
            j--;
        }
        suf[i] = last;
    }
    // for (ll i = 1; i <= n1; i++) {
    //     cout << pre[i] << ' ' << suf[i] << endl;
    // }
    ll res = n2 + 1, l, r;
    for (ll i = 1; i <= n1 + 1; i++) {
        if (pre[i - 1] < suf[i]) {
            if (res > suf[i] - pre[i - 1]) {
                res = suf[i] - pre[i - 1];
                l = pre[i - 1];
                r = suf[i];
            }
        }
    }
    if (res == n2 + 1) {
        puts("-");
    } else {
        for (int i = 1; i <= n2; i++) {
            if (i <= l || i >= r) {
                cout << t[i];
            }
        }
        puts("");
    }
}


Comments

Submit
0 Comments
More Questions

903C - Boxes Packing
887A - Div 64
755B - PolandBall and Game
808B - Average Sleep Time
1515E - Phoenix and Computers
1552B - Running for Gold
994A - Fingerprints
1221C - Perfect Team
1709C - Recover an RBS
378A - Playing with Dice
248B - Chilly Willy
1709B - Also Try Minecraft
1418A - Buying Torches
131C - The World is a Theatre
1696A - NIT orz
1178D - Prime Graph
1711D - Rain
534A - Exam
1472A - Cards for Friends
315A - Sereja and Bottles
1697C - awoo's Favorite Problem
165A - Supercentral Point
1493A - Anti-knapsack
1493B - Planet Lapituletti
747B - Mammoth's Genome Decoding
1591C - Minimize Distance
1182B - Plus from Picture
1674B - Dictionary
1426C - Increase and Copy
520C - DNA Alignment